package arrray;

import java.util.Arrays;

/**
 * @author huangxianjin
 * @date 2025/8/11 22:33
 * @description "轮转数组"
 */
public class LC_189 {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, -100, 3, 99};
        int k = 2;
        new LC_189().rotate(nums, k);
    }

    //自己的做法--System.arraycopy()+临时数组
    public void rotate(int[] nums, int k) {
        //防止k>nums.length
        k = k % nums.length;
        if (k == 0) {
            return;
        }
        int[] tempArr = new int[nums.length];
        System.arraycopy(nums, nums.length - k, tempArr, 0, k);
        System.arraycopy(nums, 0, tempArr, k, nums.length - k);
//        nums = Arrays.copyOf(tempArr, tempArr.length); //此种方式会创建一个新的数组，并没有改变原数组
//        for (int i = 0; i < tempArr.length; i++) {
//            nums[i] = tempArr[i];
//        }
        //优化
        System.arraycopy(tempArr, 0, nums, 0, nums.length);
    }

    //官方解法1-额外的数组
    public void rotate2(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    //官方解法2-数组翻转
    public void rotate3(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }
}
